<?php
/**
 * 视图缓存命令：替代 php artisan view:cache
 */

namespace Jammiest\SwigeCore\Console\Commands\Cache;

use Jammiest\SwigeCore\Console\Commands\Command;
use Jammiest\SwigeCore\Tools\Path;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'view:cache')]
class ViewCommand extends Command
{

    protected function configure()
    {
        $this->setDescription('缓存视图文件中');
    }

    protected function execute(InputInterface $input, OutputInterface $output):int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('缓存视图文件');
        
        try {
            $cacheDir = Path::getBasePath('storage/framework/views');
            // $cacheDir = storage_path('framework/views');
            if (!is_dir($cacheDir)) {
                mkdir($cacheDir, 0755, true);
            }
            
            // 编译所有视图文件
            $compiled = $this->compileViews();
            
            $io->success('视图缓存完成: ' . count($compiled) . ' 个文件已编译');
            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            $io->error('视图缓存失败: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }

    private function compileViews()
    {
        $compiled = [];
        $viewFiles = glob(Path::getBasePath('resource/views/**/*.php'));
        
        foreach ($viewFiles as $viewFile) {
            $compiledFile = Path::getBasePath('storage/framework/views/' . md5($viewFile) . '.php');
            // $compiledFile = storage_path('framework/views/' . md5($viewFile) . '.php');
            
            // 简单的视图编译（移除注释和空白）
            $content = file_get_contents($viewFile);
            $content = preg_replace('/\{{\-\-.+?\-\-\}\}/s', '', $content); // 移除注释
            $content = preg_replace('/^\s+/m', '', $content); // 压缩空白
            
            file_put_contents($compiledFile, $content);
            $compiled[] = $viewFile;
        }
        
        return $compiled;
    }
}